package com.hktf.uilib.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.hktf.corelib.utils.Config;
import com.hktf.corelib.utils.FileUtil;
import com.hktf.corelib.utils.LogMds;
import com.hktf.uilib.R;
import com.hktf.uilib.app.BaseActivity;
import com.hktf.uilib.utils.DlgUtils;


public class ProtocolTextViewActivity extends BaseActivity {

    private WebView mWebView;
    private int flag;
    private String url;


    @Override
    public int getLayoutResID() {
        return R.layout.activity_textview_protocol;
    }


    @Override
    public void initListener() {
        setBackClick();
    }

    @Override
    public void initData() {

    }

    private TextView tv_submit;
    private String title;


    public void initView() {

        tv_submit = findViewById(R.id.tv_submit);
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        mWebView = findViewById(R.id.wv);
        //        webView=findViewById(R.id.webview);
        Intent intent = getIntent();
        if (intent != null) {
            title = intent.getStringExtra("title");
            url = intent.getStringExtra("url");
            flag = intent.getIntExtra("flag", 0);
        }
        //        if (Config.userInfo != null&&flag==) {
        //            StationInfo station = Config.userInfo.getStation();
        //            if (station != null) {
        //                CNS cnsByType = station.getCnsByType(flag + "");
        //                if (cnsByType != null) {
        //                    url=cnsByType.getData();
        //                }
        //            }
        //        }

        LogMds.e("cdz", "url=" + url);
        switch (flag) {
            case 0://隐私政策
                setTitle("隐私政策");
                url = "http://driver.bjyixiong.com/private.htm";
                break;
            case 1://个人信息收集清单
                setTitle("用户协议");
                url = "http://driver.bjyixiong.com/user_protocol.htm";
                break;
            case 2://第三方信息共享清单
                setTitle("第三方信息共享清单");
                break;
            case 3://需要签署的承诺书
                break;
            case 4:
                break;
            case 5://轮播图
                setTitle("");
                break;
            case 6://带货王
                setTitle("");
                break;
            case 7://联通统一认证服务协议
                setTitle(title);
                break;
            case 8://联通统一认证服务协议
                setTitle("");
                url = "http://driver.bjyixiong.com/star.html";
                break;
            case 9://ai助手
                setTitle("");
                url = "https://ai.yixiong.cc:15000/ui/chat/bbab3fcf9572e8e0";
                break;

        }

        //        if(true){
        //            initWebView();
        //            return;
        //        }
        DlgUtils.showLoading(this, "正在加载中...");

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);

                LogMds.i("cdz", "网页开始加载啦.....url=" + url);
                //                DlgUtils.showWritDlg(WebViewActivity.this);

            }

            //网页加载完成时调用，隐藏加载提示旋转进度条
            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
                String title = mWebView.getTitle();
                if (!TextUtils.isEmpty(title)) {
                    //                    tvTitle.setText(title);
                }
                DlgUtils.disMissDlg();
            }

            //网页加载失败时调用，隐藏加载提示旋转进度条
            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // TODO Auto-generated method stub
                DlgUtils.disMissDlg();
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogMds.i("cdz", "重定向url=" + url);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                resend.sendToTarget();
            }


        });


        WebSettings webSettings = mWebView.getSettings();
        webSettings.setSupportZoom(true);          //支持缩放

        webSettings.setJavaScriptEnabled(true);    //启用JS脚本
        //        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        //屏幕适配
        //webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        if (flag == 4 || flag == 6 || flag == 9) {
            FileUtil.createDir(Config.getCache());
            // 开启DOM storage API 功能
            webSettings.setDomStorageEnabled(true);
            // 开启database storage API功能
            webSettings.setDatabaseEnabled(true);
            //            webSettings.setAppCachePath(Config.getCache());
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            //            webSettings.setAppCacheEnabled(true);
            webSettings.setBuiltInZoomControls(false);  //启用内置缩放装置
            //            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            //            webSettings.setBuiltInZoomControls(true);  //启用内置缩放装置
        } else if (flag < 4) {
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            webSettings.setBuiltInZoomControls(true);  //启用内置缩放装置
        }
        if (flag == 5) {
            webSettings.setBuiltInZoomControls(false);  //启用内置缩放装置
        }

        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);//设置渲染优先级
        //webSettings.setBlockNetworkImage(true);//窗口加载完成后 再开始渲染图片

        //        mWebView.loadUrl(url);
        if (flag == 9) {
            webSettings.setDomStorageEnabled(true);
            webSettings.setMediaPlaybackRequiresUserGesture(false);

            mWebView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onPermissionRequest(PermissionRequest request) {
                    ProtocolTextViewActivity.this.onPermissionRequest(request);
                }
            });
        }

        //        String data="<iframe\n" +
        //                "src=\"https://ai.yixiong.cc:15000/ui/chat/1b71b40db0978ab4\"\n" +
        //                "style=\"width: 100%; height: 100%;\"\n" +
        //                "frameborder=\"0\"\n" +
        //                "allow=\"microphone\">\n" +
        //                "</iframe>";
        //        mWebView.loadData(data,"text/html","UTF-8");
        mWebView.loadUrl(url);


    }

    private void onPermissionRequest(PermissionRequest request) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //            PermissionHelper.check((BaseActivity) context, new PermissionHelper.MyPermissionListener() {
            //                        @Override
            //                        public void onSuccess() {
            //                            //直接同意即可     deny是拒绝
            //                            request.grant(request.getResources());
            //                        }
            //
            //                        @Override
            //                        public void onFail() {
            //
            //                        }
            //                    }
            //                    ,context.getString(R.string.audio_tip1)
            //                    ,context.getString(R.string.audio_tip2)
            //                    , android.Manifest.permission.RECORD_AUDIO
            //
            //            );
        }
    }

    //    private void initWebView(){
    //        com.tencent.smtt.sdk.WebSettings webSetting = webView.getSettings();
    //        webSetting.setJavaScriptEnabled(true);
    //        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
    //        webSetting.setAllowFileAccess(true);
    ////        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    //        webSetting.setSupportZoom(true);
    //        webSetting.setBuiltInZoomControls(false);
    //        webSetting.setUseWideViewPort(true);
    //        webSetting.setSupportMultipleWindows(true);
    //        // webSetting.setLoadWithOverviewMode(true);
    //        webSetting.setAppCacheEnabled(true);
    //        // webSetting.setDatabaseEnabled(true);
    //        webSetting.setDomStorageEnabled(true);
    //        webSetting.setGeolocationEnabled(true);
    //        //        webView.loadUrl("http://soft.imtt.qq.com/browser/tes/feedback.html");
    //        webView.loadUrl(url);
    //        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
    //
    //        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
    ////        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
    //        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
    //        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
    //
    //        getWindow().setFormat(PixelFormat.TRANSLUCENT);
    //
    //        webView.getView().setOverScrollMode(View.OVER_SCROLL_ALWAYS);
    //    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mWebView != null) {

            mWebView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        try {
            if (mWebView != null) {
                if (flag != 4 && flag != 6 && flag != 9) {
                    mWebView.clearCache(true);
                    mWebView.clearHistory();
                }
                ViewGroup parent = (ViewGroup) mWebView.getParent();
                if (parent != null) {
                    parent.removeView(mWebView);
                }
                mWebView.removeAllViews();
                mWebView.destroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }


    @Override
    public void onBackPressed() {
        if (mWebView == null) {
            return;
        }
        LogMds.i("cdz", "...当前url=" + mWebView.getUrl());
        /*if(!isSave){
            cancel();
        }*/

        if (mWebView.canGoBack()) {
            mWebView.goBack();
            //            mWebView.clearCache(true);
            //            mWebView.clearHistory();
            LogMds.i("cdz", "...返回url=" + mWebView.getUrl());
        } else {
            super.onBackPressed();
        }
    }

}
